package cn.z2huo.knowledge.collection.list.arraylist.randomaccess;

import org.apache.commons.lang3.RandomStringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>ArrayList 随机访问
 *
 * <p>fori 遍历和 迭代器遍历速度对比
 *
 * @author z2huo
 */
class RandomAccessTest {

    public List<String> initList(int count) {
        ArrayList<String> strings = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            strings.add(RandomStringUtils.randomAlphabetic(10));
        }
        return strings;
    }

    public void forTest(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i);
        }
    }

    public void iteratorTest(List<String> list) {
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            iterator.next();
        }
    }

    public static void main(String[] args) {

        // 1 亿 条数据，forTest: 35 ms，iteratorTest: 45 ms
        int count = 1_000_000_00;

        RandomAccessTest randomAccessTest = new RandomAccessTest();
        List<String> strings = randomAccessTest.initList(count);
        System.out.println("init list success");

        long start, end;

        start = System.currentTimeMillis();
        randomAccessTest.forTest(strings);
        end = System.currentTimeMillis();
        System.out.println("forTest: " + (end - start) + " ms");

        start = System.currentTimeMillis();
        randomAccessTest.iteratorTest(strings);
        end = System.currentTimeMillis();
        System.out.println("iteratorTest: " + (end - start) + " ms");
    }

}
